package com.mes.cloud.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mes.cloud.dao.BmeBcDAO;
import com.mes.cloud.dao.BmeBcFiledDAO;
import com.mes.cloud.dao.BmeBcJoinDAO;
import com.mes.cloud.dto.BmeBcDTO;
import com.mes.cloud.dto.BmeBcFiledDTO;
import com.mes.cloud.dto.BmeBcJoinDTO;
import com.mes.cloud.service.BmeBcService;
import com.mes.cloud.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BC基础表
 *
 * @author xhy
 * @version 1.0
 * @date 2019/05/09 16:00
 */
@Service
public class BmeBcServiceImpl implements BmeBcService {
    /**
     * 日志记录  其中在记录的时候 Class代表类名 Method代表方法名 Param代表参数
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BmeBcServiceImpl.class);
    private static final Map MAP_VL = Maps.newHashMap();

    static {
        MAP_VL.put("varchar", "widget-input-text");
        MAP_VL.put("timestamp", "widget-date-picker");
        MAP_VL.put("datetime", "widget-date-picker");
        MAP_VL.put("date", "widget-date-picker");
        MAP_VL.put("input", "widget-input-text");
    }

    @Autowired
    private BmeBcDAO bmeBcDAO;
    @Autowired
    private BmeBcFiledDAO bmeBcFiledDAO;
    @Autowired
    private BmeBcJoinDAO bmeBcJoinDAO;

    /**
     * 根据条件获取BC基础表列表
     *
     * @param condition
     * @return List<BmeBcDTO>
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    public List<BmeBcDTO> getBmeBcList(Map<Object, Object> condition) {
        LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcList: InParam condition: {}", condition.toString());
        List<BmeBcDTO> bmeBcList = bmeBcDAO.getBmeBcList(condition);
        if (bmeBcList == null) {
            LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcList: OutParam bmeBcList==null");
            return null;
        }
        LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcList: OutParam bmeBcList: {}", bmeBcList.toString());
        return bmeBcList;
    }

    /**
     * 获取BC基础表的最大记录数
     *
     * @param condition
     * @return long
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    public long getBmeBcCount(Map<Object, Object> condition) {
        LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcCount: InParam condition: {}", condition.toString());
        long count = bmeBcDAO.getBmeBcCount(condition);
        if (count == 0) {
            LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcCount: OutParam count==0");
            return 0;
        }
        LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcCount: OutParam count: {}", count);
        return count;
    }

    /**
     * 新增BC基础表
     *
     * @param bmeBcDTO
     * @return long
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    public long insertBmeBc(BmeBcDTO bmeBcDTO) {
        bmeBcDTO.setId(UuId.getShortUuid());
        LOGGER.info("Class BmeBcServiceImpl: Method insertBmeBc: InParam condition: {}", bmeBcDTO.toString());
        long count = bmeBcDAO.insertBmeBc(bmeBcDTO);
        if (count == 0) {
            LOGGER.info("Class BmeBcServiceImpl: Method insertBmeBc: OutParam count==0");
            return 0;
        }
        LOGGER.info("Class BmeBcServiceImpl: Method insertBmeBc: OutParam count: {}", count);
        return count;
    }

    /**
     * 更新BC基础表
     *
     * @param bmeBcDTO
     * @return long
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    public long updateBmeBc(BmeBcDTO bmeBcDTO) {
        LOGGER.info("Class BmeBcServiceImpl: Method updateBmeBc: InParam condition: {}", bmeBcDTO.toString());
        long count = bmeBcDAO.updateBmeBc(bmeBcDTO);
        if (count == 0) {
            LOGGER.info("Class BmeBcServiceImpl: Method updateBmeBc: OutParam count==0");
            return 0;
        }
        LOGGER.info("Class BmeBcServiceImpl: Method updateBmeBc: OutParam count: {}", count);
        return count;
    }

    /**
     * 删除BC基础表
     *
     * @param id
     * @return long
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    public long delBmeBcById(String id) {
        LOGGER.info("Class BmeBcServiceImpl: Method delBmeBcById: InParam id: {}", id);
        long count = bmeBcDAO.delBmeBcById(id);
        if (count == 0) {
            LOGGER.info("Class BmeBcServiceImpl: Method delBmeBcById: OutParam count==0");
            return 0;
        }
        LOGGER.info("Class BmeBcServiceImpl: Method delBmeBcById: OutParam count: {}", count);
        return count;
    }

    /**
     * 根据BC基础表标识获取BC基础表
     *
     * @param id
     * @return long
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    public BmeBcDTO getBmeBcById(String id) {
        LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcById: InParam id: {}", id);
        BmeBcDTO bmeBcDTO = bmeBcDAO.getBmeBcById(id);
        if (bmeBcDTO == null) {
            LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcById: OutParam bmeBcDTO==null");
            return null;
        }
        LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcById: OutParam bmeBcDTO: {}", bmeBcDTO.toString());
        return bmeBcDTO;
    }

    /**
     * 根据条件获取BC基础表列表
     *
     * @param condition
     * @return List<BmeBcDTO>
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    public CommPager<BmeBcDTO> getBmeBcListPage(Map<Object, Object> condition) {
        LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcListPage: InParam condition: {}", condition.toString());
        int pageIndex = condition.get("pageIndex") == null ? 0 : Integer.valueOf(condition.get("pageIndex").toString());
        int pageSize = condition.get("pageSize") == null ? 10 : Integer.valueOf(condition.get("pageSize").toString());
        Page<BmeBcDTO> page = PageHelper.startPage(pageIndex, pageSize, true);
        List<BmeBcDTO> bcDTOList = bmeBcDAO.getBmeBcList(condition);
        if (bcDTOList == null) {
            LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcListPage: OutParam bcDTOList==null");
            return null;
        }
        LOGGER.info("Class BmeBcServiceImpl: Method getBmeBcListPage: OutParam bcDTOList: {}", bcDTOList.toString());
        CommPager commPager = new CommPager(page,bcDTOList);
        return commPager;
    }

    /**
     * 对BC_Filed基础表标进行批量删除操作
     *
     * @param map
     * @return long
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    @Transactional
    public long batchDelete(Map<Object, Object> map) {
        LOGGER.info("Class BmeBcServiceImpl: Method batchDelete: InParam map: {}", map);
        List<Long> longs = (List<Long>) map.get("ids");
        long count = bmeBcDAO.batchDelete(longs);
        if (count == 0) {
            LOGGER.info("Class BmeBcServiceImpl: Method batchDelete: OutParam count==0");
            return 0;
        }
        LOGGER.info("Class BmeBcServiceImpl: Method batchDelete: OutParam count: {}", count);
        return count;
    }

    /**
     * 对bme_bc的配置参生对应的sql
     *
     * @param bcId
     * @return long
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    public long getSql(String bcId) {
        LOGGER.info("Class BmeBcServiceImpl: Method getSql: InParam bcId: {}", bcId);
        StringBuffer viewSql = null;
        long count = 0;
        try {
            BmeBcDTO bmeBcDTO = bmeBcDAO.getBmeBcById(bcId);
            if (bmeBcDTO == null) {
                LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam baseMap==null");
                return 0;
            }
            String tbName = bmeBcDTO.getBcTable();
            String tbNameAlias = "T0";
            Map mapFiled = Maps.newHashMap();
            mapFiled.put("pid", bcId);
            List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);
            if (bmeBcFiledList == null || bmeBcFiledList.size() < 1) {
                LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam list==null");
                return 0;
            }
            //用来拼接sql的前半部分查询
            StringBuffer stringBuffer = new StringBuffer("select ");
            //用来拼接sql的后半部分查询
            StringBuffer stringBuffer1 = new StringBuffer(" from ");
            stringBuffer1.append(tbName).append(" ").append(tbNameAlias);
            List list1 = Lists.newArrayList();
            String joinSlaveTable;
            String slaveBie;
            Map<String, Object> mapCach = Maps.newHashMap();
            BmeBcJoinDTO joinMap;
            int length = bmeBcFiledList.size();
            for (int i = 0; i < length; i++) {
                BmeBcFiledDTO bmeBcFiledDTO = bmeBcFiledList.get(i);
                if (bmeBcFiledDTO == null) {
                    LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam bmeBcFiledDTO==null");
                    return 0;
                }
                String calculation = bmeBcFiledDTO.getCalculation();
                String filed = bmeBcFiledDTO.getField();
                String clunm = bmeBcFiledDTO.getColunm();
                String customType = bmeBcFiledDTO.getFieldCustomType();

                //如果是join字段
                if (StringUtils.isNotBlank(bmeBcFiledDTO.getFieldJoin())) {
                    String joinIds = bmeBcFiledDTO.getFieldJoin();
                    String joinIdNmae = bcId + joinIds;
                    //加个临时的缓存 主要对多个字段设计同一个join的数据防止进行多次查询join表
                    if (!mapCach.containsKey(joinIdNmae) || mapCach == null) {
                        HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();
                        objectObjectHashMap.put("joinName", joinIds);
                        objectObjectHashMap.put("pid", bcId);
                        BmeBcJoinDTO bmeBcJoinDTO = bmeBcJoinDAO.getBmeBcJoinByIdName(objectObjectHashMap);
                        mapCach.put(joinIdNmae, bmeBcJoinDTO);
                    }
                    //获取join详情
                    joinMap = (BmeBcJoinDTO) mapCach.get(joinIdNmae);
                    //获取join从表
                    joinSlaveTable = joinMap.getJoinSlaveTable().toLowerCase();
                    //获取join主表别名
                    String joinMasterAlias =  joinMap.getJoinMasterAlias();
                    //获取join从表别名
                    String joinSlaveAlias = joinMap.getJoinSlaveAlias();
                    //获取join名称
                    slaveBie = joinMap.getName();
                    //获取join主表字段
                    String masterField = joinMap.getJoinMasterField();
                    //获取join从表字段
                    String slaveField = joinMap.getJoinSlaveField();
                    //获取join关联方式
                    String joinWay = joinMap.getJoinWay();
                    //关联条件
                    String joinCondition = joinMap.getJoinCondition();
                    //对于中间有出现计算字段的进行处理
                    if (Constants.FieldCustomType.CUSTOMTYPE_CALCULATION.equals(bmeBcFiledDTO.getFieldCustomType())) {
                        //这里说明有计算字段
                        if (StringUtils.isNotBlank(bmeBcFiledDTO.getCalculation())) {
                            stringBuffer.append("(select ").append(calculation).append(" from ")
                                    .append(joinSlaveTable).append(" ").append(slaveBie)
                                    .append(" where ").append(tbNameAlias).append(".")
                                    .append(masterField).append(" = ").append(slaveBie)
                                    .append(".").append(slaveField).append(") as `")
                                    .append(filed).append("`,");
                        }
                    } else {
                        stringBuffer.append(joinSlaveAlias).append(".").append(clunm).append(" as `").append(filed).append("`,");
                    }
                    if (joinWay.equals(Constants.JoinWay.JOIN_WAY_Y) && !Constants.FieldCustomType.CUSTOMTYPE_CALCULATION.equals(customType)) {
                        if (list1 == null || !list1.contains(joinIdNmae)) {
                            stringBuffer1.append(" join ").append(joinSlaveTable).append(" ").append(joinSlaveAlias).append(" on ")
                                    .append(joinMasterAlias).append(".").append(masterField).append(" = ").append(joinSlaveAlias).append(".")
                                    .append(slaveField);
                            list1.add(joinIdNmae);
                        }
                    } else {
                        if (list1 == null || !list1.contains(joinIdNmae) && !Constants.FieldCustomType.CUSTOMTYPE_CALCULATION.equals(customType)) {
                            stringBuffer1.append(" left join ").append(joinSlaveTable).append(" ").append(joinSlaveAlias).append(" on ")
                                    .append(joinSlaveAlias).append(".").append(masterField).append(" = ").append(joinSlaveAlias).append(".")
                                    .append(slaveField);
                            list1.add(joinIdNmae);
                        }
                    }
                    //实体字段
                } else {
                    stringBuffer.append(tbNameAlias).append(".").append(clunm).append(" as `").append(filed).append("`,");
                }
            }

            int selectBufferInt = stringBuffer.lastIndexOf(",");
            int fromBufferInt = stringBuffer1.lastIndexOf(",");
            if (stringBuffer.length() - 1 == selectBufferInt) {
                stringBuffer.deleteCharAt(selectBufferInt);
            }
            if (fromBufferInt == stringBuffer1.length() - 1) {
                stringBuffer1.deleteCharAt(fromBufferInt);
            }

            viewSql = stringBuffer.append(stringBuffer1);
            //过滤掉字段被软删除的数据
            if (StringUtils.isNotBlank(bmeBcDTO.getBcFilter())) {
                viewSql.append(" where " + bmeBcDTO.getBcFilter());
            }
            LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam viewSql： {}", viewSql);
            //将缓存的数据及时的进行清理 防止溢出
            if (mapCach != null) {
                mapCach.clear();
            }
            BmeBcDTO bmeBc = new BmeBcDTO();
            bmeBc.setId(bcId);
            bmeBc.setBcQuerysql(viewSql.toString());
            count = bmeBcDAO.updateBmeBc(bmeBc);
            if (count < 1) {
                LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam count=={}", count);
                return 0;
            }
            LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam viewSql： {}", viewSql);
        } catch (Exception e) {
            LOGGER.error("Class BmeBcServiceImpl: Method getSql: OutParam e： {}", e.getMessage());
        }
        return count;
    }

    /**
     * 生成sql
     * 1:获取bc对应的字段，字段类型有客制类型 实体类型:Entity;计算类型:Calculation,约束类型:Virtual，生成select字段
     * 2：字段类型是join类型，拼接join关联
     * 3：更新bc的BcQuerysql字段值
     *
     * @param bcId
     * @return long
     * @author wxm
     */
    @Override
    public long getSqlNew(String bcId) {
        LOGGER.info("Class BmeBcServiceImpl: Method getSqlNew: InParam bcId: {}", bcId);
        StringBuffer viewSql = null;
        long count = 0;
        try {
            //获取BC信息
            BmeBcDTO bmeBcDTO = bmeBcDAO.getBmeBcById(bcId);
            if (bmeBcDTO == null) {
                LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam baseMap==null");
                return 0;
            }
            //获取BC对应的主表
            String tbName = bmeBcDTO.getBcTable();
            //BC主表对应的别名默认为T0
            String tbNameAlias = "T0";
            Map mapFiled = Maps.newHashMap();
            mapFiled.put("pid", bcId);
            //获取BC对应的字段
            List<BmeBcFiledDTO> bmeBcFiledList = bmeBcFiledDAO.getBmeBcFiledList(mapFiled);
            if (bmeBcFiledList == null || bmeBcFiledList.size() < 1) {
                LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam list==null");
                return 0;
            }
            //获取字段中customType=Join  字段的join放到list
            List<String> joinNameList = getJoinName(bmeBcFiledList);
            Map<String, BmeBcJoinDTO> mapJoin = new HashMap<>();
            List<BmeBcJoinDTO> bmeBcJoinDTOList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(joinNameList)){
                //获取join列表
                bmeBcJoinDTOList = bmeBcJoinDAO.selectByNames(joinNameList,bcId);

                //存放字段用到的join -- joinname  join实体
                mapJoin = listToMap(bmeBcJoinDTOList);
            }

            //用来拼接sql的select部分
            StringBuffer stringBufferSelect = new StringBuffer("select DISTINCT ");
            int length = bmeBcFiledList.size();
            for (int i = 0; i < length; i++) {
                BmeBcFiledDTO bmeBcFiledDTO = bmeBcFiledList.get(i);
                if (bmeBcFiledDTO == null) {
                    LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam bmeBcFiledDTO==null");
                    return 0;
                }
                String calculation = bmeBcFiledDTO.getCalculation();
                //字段别名
                String filed = bmeBcFiledDTO.getField();
                //数据库字段名
                String colunm = bmeBcFiledDTO.getColunm();
                //字段类型 实体类型:Entity;计算类型:Calculation;约束类型:Virtual;关联类型:Join
                String customType = bmeBcFiledDTO.getFieldCustomType();

                //如果是实体字段
                //如果是join字段
                //如果是计算字段
                //如果是计算字段
                if ("Entity".equals(customType)) {
                    stringBufferSelect.append(tbNameAlias).append(".").append(colunm).append(" as `").append(filed).append("`,");
                }
                if ("Join".equals(customType)) {
                    String joinName = bmeBcFiledDTO.getFieldJoin();
                    //获取join关系，需要使用join的别名
                    BmeBcJoinDTO bmeBcJoinDTO = null;
                    if (mapJoin.containsKey(joinName)) {
                        bmeBcJoinDTO = mapJoin.get(joinName);
                        stringBufferSelect.append(bmeBcJoinDTO.getJoinSlaveAlias()).append(".").append(colunm).append(" as `").append(filed).append("`,");
                    }

                }
                if ("Calculation".equals(customType)) {
                    //业务待确认
                    stringBufferSelect.append("(").append(calculation).append(") AS `").append(filed).append("`,");
                }
                if ("Virtual".equals(customType)) {
                    //业务待确认
                }
                if ("CrossJoin".equals(customType)) {
                    //跨库字段不需要处理
                }

            }
            //用来拼接sql的from
            StringBuffer stringBufferFrom = new StringBuffer(" from ");
            stringBufferFrom.append(tbName).append(" ").append(tbNameAlias);
            if (CollectionUtils.isNotEmpty(bmeBcJoinDTOList)) {
                for (BmeBcJoinDTO bmeBcJoinDTO : bmeBcJoinDTOList) {
                    //获取join从表
                    String joinSlaveTable = bmeBcJoinDTO.getJoinSlaveTable();
                    //获取join从表别名
                    String joinSlaveAlias = bmeBcJoinDTO.getJoinSlaveAlias();

                    //获取join主表
                    String joinMasterTable = bmeBcJoinDTO.getJoinMasterTable();
                    //获取join主表别名
                    String joinMasterAlias = bmeBcJoinDTO.getJoinMasterAlias();

                    //获取join主表字段
                    String masterField = bmeBcJoinDTO.getJoinMasterField();
                    //获取join从表字段
                    String slaveField = bmeBcJoinDTO.getJoinSlaveField();

                    //获取join关联方式
                    String joinWay = bmeBcJoinDTO.getJoinWay();

                    String joinCondition = bmeBcJoinDTO.getJoinCondition();
                    if (Constants.JoinWay.JOIN_WAY_Y.equals(joinWay)) {
                        stringBufferFrom.append(" inner join ");
                    } else {
                        stringBufferFrom.append(" left join ");
                    }
                    stringBufferFrom.append(joinSlaveTable).append(" ").append(joinSlaveAlias).append(" on ")
                            .append(joinMasterAlias).append(".").append(masterField).append(" = ").append(joinSlaveAlias).append(".")
                            .append(slaveField);
                    //增加关联条件
                    if(!StringUtils.isEmpty(joinCondition)){
                        stringBufferFrom.append(" ").append(joinCondition);
                    }
                }
            }


            int selectBufferInt = stringBufferSelect.lastIndexOf(",");
            int fromBufferInt = stringBufferFrom.lastIndexOf(",");
            if (stringBufferSelect.length() - 1 == selectBufferInt) {
                stringBufferSelect.deleteCharAt(selectBufferInt);
            }
            if (fromBufferInt == stringBufferFrom.length() - 1) {
                stringBufferFrom.deleteCharAt(fromBufferInt);
            }

            viewSql = stringBufferSelect.append(stringBufferFrom);
            //过滤掉字段被软删除的数据
            if (StringUtils.isNotBlank(bmeBcDTO.getBcFilter())) {
                viewSql.append(" where " + bmeBcDTO.getBcFilter());
            }
            LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam viewSql： {}", viewSql);

            BmeBcDTO bmeBc = new BmeBcDTO();
            bmeBc.setId(bcId);
            bmeBc.setBcQuerysql(viewSql.toString());
            count = bmeBcDAO.updateBmeBc(bmeBc);
            if (count < 1) {
                LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam count=={}", count);
                return 0;
            }
            LOGGER.info("Class BmeBcServiceImpl: Method getSql: OutParam viewSql： {}", viewSql);
        } catch (Exception e) {
            LOGGER.error("Class BmeBcServiceImpl: Method getSql: OutParam e： {}", e.getMessage());
        }
        return count;
    }

    private Map<String,BmeBcJoinDTO> listToMap(List<BmeBcJoinDTO> bmeBcJoinDTOList) {
        Map<String, BmeBcJoinDTO> mapJoin = Maps.newHashMap();
        if(CollectionUtils.isEmpty(bmeBcJoinDTOList)){
            return mapJoin;
        }
        for(BmeBcJoinDTO bmeBcJoinDTO : bmeBcJoinDTOList){
            mapJoin.put(bmeBcJoinDTO.getName(),bmeBcJoinDTO);
        }
        return mapJoin;
    }


    private List<String> getJoinName(List<BmeBcFiledDTO> bmeBcFiledList) {
        List<String> joinNameList = new ArrayList<>();
        if(CollectionUtils.isEmpty(bmeBcFiledList)){
            return joinNameList;
        }
        for (BmeBcFiledDTO bmeBcFiledDTO : bmeBcFiledList) {
            //如果字段类型是join，获取join的值
            if ("Join".equals(bmeBcFiledDTO.getFieldCustomType())) {
                //获取join的值
                joinNameList.add(bmeBcFiledDTO.getFieldJoin());
            }
        }
        return joinNameList;
    }

    /**
     * 对bme_bc的配置参生对应的初始化表字段
     *
     * @param bcId
     * @return long
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Transactional
    @Override
    public JSONResult initFiled(String bcId) {
        LOGGER.info("Class BmeBcServiceImpl: Method initFiled: bcId :{}", bcId);
        long count = 0;
        try {
            //bmeBcFiledDAO.delBmeBcFiledByPid(bcId);
            //查询bc信息
            BmeBcDTO bmeBcDTO = bmeBcDAO.getBmeBcById(bcId);
            Map<Object, Object> map = Maps.newHashMap();
            map.put("dbName",bmeBcDTO.getBcDatasource());
            map.put("tbName", bmeBcDTO.getBcTable());
            //根据bc信息查询filed信息
            //filed表中信息
            List<Map> mapFiledList = bmeBcFiledDAO.getBcFiledList(bcId);
            //数据库中数据字典信息
            List<Map> mapTableList = bmeBcDAO.getTableSysFile(map);
            if (mapTableList == null || mapTableList.size() < 1) {
                LOGGER.info("Class BmeBcServiceImpl: Method initFiled: mapList :{}", mapTableList);
                return JSONResult.fail(201, "业务数据异常");
            }
            List<BmeBcFiledDTO> initFiledList = Lists.newArrayList();
            if (mapFiledList != null && mapFiledList.size() > 0) {
                //bcFiled表中存在数据，则与数据字典中查到的信息对比：如果数据字典中表结构部分不在bcFiled表中，将不再的部分插入bcFiled表
                List<String> list = getLackFiledList(mapFiledList, mapTableList);
                if (list.size() == 0) {
                    return JSONResult.fail(201, "主表数据已全部存在，无需再次生成！");
                }
                map.put("columnNames",list);
                List<Map> mapList = bmeBcDAO.getTableSysFile(map);
                initFiledList = getBmeBcFiledList(mapList, bcId);
            } else {
                //bcFiled表中无数据，将数据字典中查到的信息插入bcFiled表
                initFiledList = getBmeBcFiledList(mapTableList, bcId);
            }
            count = bmeBcFiledDAO.batchInitFiled(initFiledList);
            if (count == 0) {
                LOGGER.info("Class BmeBcServiceImpl: Method initFiled OutParam: count :{}", count);
                return JSONResult.fail(201, "业务数据异常");
            }
        } catch (Exception e) {
            LOGGER.error("Class BmeBcServiceImpl: Method initFiled OutParam: e :{}", e.getMessage());
            return JSONResult.fail(201, "业务数据异常");
        }
        return JSONResult.success(count);

    }

    private List<String> getLackFiledList(List<Map> mapFiledList, List<Map> mapTableList) {
        List<String> filedList = Lists.newArrayList();
        for (int i = 0; i < mapFiledList.size(); i++) {
            Map<String, String> map = mapFiledList.get(i);
            filedList.add(map.get("column_name"));
        }
        List<String> tableList = Lists.newArrayList();
        for (int i = 0; i < mapTableList.size(); i++) {
            Map<String, String> map = mapTableList.get(i);
            tableList.add(map.get("column_name"));
        }
        List<String> list = (List<String>) CollectionUtils.subtract(tableList, filedList);
        return list;
    }

    private List<BmeBcFiledDTO> getBmeBcFiledList(List<Map> mapList, String bcId) {
        List<BmeBcFiledDTO> initFiledList = Lists.newArrayList();
        for (int i = 0; i < mapList.size(); i++) {
            Map map = mapList.get(i);
            if (map == null) {
                LOGGER.info("Class BmeBcServiceImpl: Method initFiled: map :{}", map);
                JSONResult.fail(201, "业务数据异常");
            }
            getBmeBcFiledDto(bcId, initFiledList, map);
        }
        return initFiledList;
    }

    private void getBmeBcFiledDto(String bcId, List<BmeBcFiledDTO> initFiledList, Map map) {
        String maxLength = map.get("character_maximum_length") != null ? map.get("character_maximum_length").toString() : null;
        String column_comment = map.get("column_comment").toString();
        String column_name = map.get("column_name").toString();
        String data_type = map.get("data_type").toString();
        if(column_name.equals("project_on_line_date")){
            System.out.println();
        }
        String varType;
        if (data_type.equalsIgnoreCase(Constants.MYSQLTY.VARCHER) || data_type.equalsIgnoreCase(Constants.MYSQLTY.DATE) || data_type.equalsIgnoreCase(Constants.MYSQLTY.DATETIME) || data_type.equalsIgnoreCase(Constants.MYSQLTY.TIMESTAM)) {
            varType = MAP_VL.get(data_type).toString();
        } else {
            varType = MAP_VL.get(Constants.MYSQLTY.INPUT).toString();
        }
        String extra = map.get("extra") != null ? map.get("extra").toString() : null;
        String isprikey = map.get("column_key") != null ? map.get("column_key").toString() : null;
        BmeBcFiledDTO bmeBcFiledDTO = new BmeBcFiledDTO();
        bmeBcFiledDTO.setType(varType);
        bmeBcFiledDTO.setId(UuId.getShortUuid());
        bmeBcFiledDTO.setPid(bcId);
        bmeBcFiledDTO.setExtra(extra);
        bmeBcFiledDTO.setIsPk(isprikey);
        bmeBcFiledDTO.setName(column_comment);
        bmeBcFiledDTO.setDs(column_comment);
        bmeBcFiledDTO.setField(StringUtils.underlineToCamelhump(column_name));
        bmeBcFiledDTO.setColunm(column_name);
        bmeBcFiledDTO.setFieldType(data_type);
        bmeBcFiledDTO.setFieldLength(maxLength);
        initFiledList.add(bmeBcFiledDTO);
    }

    /**
     * 对bme_bc是否启用
     *
     * @param map
     * @return long
     * @author xhy
     * @date 2019/05/09 16:00
     */
    @Override
    public long enable(Map<Object, Object> map) {
        if (map.get("id") == null || map.get("isEnable") == null) {
            LOGGER.info("Class BmeBcServiceImpl: Method enable: map ==null");
            return 0;
        }
        return bmeBcDAO.enable(map);
    }

    @Override
    public Long batchEnable(Map<Object, Object> map) throws Exception {
        if (map.get("ids") == null) {
            LOGGER.info("Class BmeBcServiceImpl: Method enable: map ==null");
            throw new Exception("ids不能为空");
        }
        return bmeBcDAO.batchEnable((List<Long>) map.get("ids"));
    }

    @Override
    public int importExcel(MultipartFile file) throws Exception {
        String rooPath = this.getClass().getResource("/").getPath();
        //复制文件到static目录
        String path = rooPath + "/static";
        String fileName = FileUploadUtils.uploadFile(file, path);
        String filePath = FileUploadUtils.uploadFile(file, path, fileName);
        FileInputStream fis = null;
        fis = new FileInputStream(filePath);
        // 创建工具类.
        ExcelUtil<BmeBcDTO> util = new ExcelUtil<BmeBcDTO>(BmeBcDTO.class);
        List<BmeBcDTO> paramList = util.importExcel(fileName, fis);
        if (StringUtils.isEmpty(paramList)) {
            throw new Exception("数据为空！");
        }
        HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();
        for (BmeBcDTO bmeBcDTO : paramList) {
            if (StringUtils.isEmpty(bmeBcDTO.getId())) {
                bmeBcDTO.setId(UuId.getShortUuid());
            } else {
                objectObjectHashMap.put("id", bmeBcDTO.getId());
                long count = bmeBcDAO.getBmeBcCount(objectObjectHashMap);
                if (count > 0) {
                    throw new Exception("数据已经存在！");
                }
            }
        }
        return bmeBcDAO.insertExcel(paramList);
    }

    @Override
    public void exportFile(Map<Object, Object> map, HttpServletResponse response) throws Exception {
        PageHelper.startPage(1, 500, true);
        List<BmeBcDTO> list = bmeBcDAO.getBmeBcList(map);
        if (list.size() == 0) {
            throw new Exception("导出数据为空！");
        }
        // 创建工具类
        ExcelUtil<BmeBcDTO> util = new ExcelUtil<BmeBcDTO>(BmeBcDTO.class);
        // 导出
        String topName = DateUtil.getDateTime("yyyyMMddHHmmss");
        util.exportFile(list, DateUtil.getDateTime(topName), topName, response);
    }
}
